#include "listdir.h"
#include "enginedirs.h"

#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>

#include <iostream>

namespace Lame3d
{
	void listDirectory(const std::string &path, std::list<std::string> &list, const std::string &prefix)
	{
		DIR *dir;
		struct dirent* cEnt;
		struct stat cEntStat;
		
		if((dir=opendir(path.c_str())) == NULL) {
			throw "Couldn't open directory for listing.";
		}
		
		while((cEnt = readdir(dir)) != NULL) {
			std::string fPath = path;
			fPath += DIRSEP;
			fPath += cEnt->d_name;
			if(stat(fPath.c_str(), &cEntStat) != 0) {
				throw "Error statting file during directory listing.";
			}
			if(S_ISREG(cEntStat.st_mode)) {
				//fPath = prefix;
				//fPath += DIRSEP;
				//fPath += cEnt->d_name;
				fPath = cEnt->d_name;
				list.push_back(fPath);
			}
		}
		closedir(dir);
	}
	
	void filterDirectory(std::list<std::string> &list, const std::list<std::string> &goodExtensions)
	{
		std::string extension;
		bool okay;
		std::list<std::string>::iterator listIt;
		std::list<std::string>::const_iterator extIt;
		for(listIt=list.begin(); listIt != list.end(); ) {
			okay = false;
			extension = getExtension(*listIt);
			for(extIt=goodExtensions.begin(); extIt != goodExtensions.end(); ++extIt) {
				if(strcasecmp(extension.c_str(), (*extIt).c_str()) == 0) {
					okay = true;
					break;
				}
			}
			if(!okay) {
				listIt = list.erase(listIt);
			} else {
				++listIt;
			}
		}
	}
	
	std::string getExtension(const std::string &path)
	{
		size_t lIdx;
		lIdx = path.find_last_of(".");
		if(lIdx < path.size() - 1) {
			return path.substr(lIdx+1);
		} else {
			return "";
		}
	}
}

// eof
